package com.omenkk.juc.synchronizedPlus;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
@Slf4j
public class MessageQueue {

    private LinkedList<Message> queue=new LinkedList();
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
        this.queue=new LinkedList();
    }

    public Message take() {
        synchronized (queue){
            while(queue.isEmpty()){
                //当没有消息的时候，wait
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //取出消息
            Message message= queue.removeFirst();
            log.debug("消费者取出消息:{}",message);
            queue.notifyAll();

            return message;
        }

    }


    public void put(Message message) {
        synchronized (queue){
            while(queue.size()==capacity){
                log.debug("库存已达上限");
                //消息满了，不能存储
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //存储消息
            log.debug("生产者放入消息:{}",message);
            queue.addLast(message);
            queue.notifyAll();
        }
    }
}
